package org.jeecg.modules.demo.wuyou.service.impl;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.config.sign.util.HttpUtils;
import org.jeecg.modules.demo.wuyou.entity.Sitemap;
import org.jeecg.modules.demo.wuyou.mapper.SitemapMapper;
import org.jeecg.modules.demo.wuyou.service.ISitemapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: sitemap
 * @Author: jeecg-boot
 * @Date: 2024-09-30
 * @Version: V1.0
 */
@Service
public class SitemapServiceImpl extends ServiceImpl<SitemapMapper, Sitemap> implements ISitemapService {
    @Autowired
    private RedisUtil redisTemplate;


    private static final String SITEMAP_CACHE_KEY = "sitemap";

    private static final String FOOT_TEMPLATE_CACHE_KEY = "foot_sitemap";
    public static final String NEWS_URL_P = "/p/";

    private static final String NEWS_URL_LOC = "https://www.51liuxue.com";

    public static final String NEWS_URL_S = "/s/";


    @Override
    public String getSitemap() {
        String sitemap = (String) redisTemplate.get(SITEMAP_CACHE_KEY);
        if (sitemap == null) {
            generateAndCacheSitemap(); // 如果缓存过期，重新生成
            sitemap = (String) redisTemplate.get(SITEMAP_CACHE_KEY);
        }
        return sitemap;
    }

    @Override
    public void generateAndCacheSitemap() {
        List<Sitemap> entries = this.list(new LambdaQueryWrapper<Sitemap>().orderByDesc(Sitemap::getLastModified));
        StringBuilder sitemapBuilder = new StringBuilder();
        sitemapBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n").append("<urlset>\n");

        for (Sitemap entry : entries) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            // 格式化 Date 对象
            String formattedDate = formatter.format(entry.getLastModified());
            sitemapBuilder.append("  <url>\n").append("    <loc>").append(entry.getUrl()).append("</loc>\n").append("    <lastmod>").append(formattedDate).append("</lastmod>\n").append("    <changefreq>").append("monthly").append("</changefreq>\n").append("    <priority>").append("0.8").append("</priority>\n").append("  </url>\n");
        }
        sitemapBuilder.append("</urlset>");
        // 存入 Redis
        redisTemplate.set(SITEMAP_CACHE_KEY, sitemapBuilder.toString(), 60 * 60);
    }

    @Override
    public HashMap<String, List<Map<String, Object>>> getSelectMap() {
        HashMap<String, List<Map<String, Object>>> stringListHashMap = (HashMap<String, List<Map<String, Object>>>) redisTemplate.get(FOOT_TEMPLATE_CACHE_KEY);
        if (stringListHashMap == null) {

            HashMap<String, List<Map<String, Object>>> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("friendly_link", this.baseMapper.selectByCondition("SELECT t.* FROM web_friendly_link t LIMIT 501", new HashMap<>()));
            objectObjectHashMap.put("web_company", this.baseMapper.selectByCondition("SELECT t.* FROM web_company t LIMIT 501", new HashMap<>()));
            objectObjectHashMap.put("web_hotshool", this.baseMapper.selectByCondition("SELECT t.* FROM web_hotshool t LIMIT 501", new HashMap<>()));
            redisTemplate.set(FOOT_TEMPLATE_CACHE_KEY, objectObjectHashMap, 60 * 60 * 2);
            return objectObjectHashMap;
        }
        return stringListHashMap;
    }
    public Boolean getHttpStatus(String Json) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost("https://scrm.51liuxue.com/api/v2/open/worksheet/addRow");

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer your_token_here");

            // 设置请求体
//            String json = "{ \"key\": \"value\" }";
            StringEntity entity = new StringEntity(Json, "UTF-8");
            httpPost.setEntity(entity);

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应
                String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> GetByCondition(String sqlStr, Map<String, Object> param) {
        return this.baseMapper.selectByCondition(sqlStr, param);
    }

}
